import React, { useState, useEffect, useCallback, useRef } from 'react';
import { connect } from 'dva';
import { Tabs, Tree, Button, Input, Modal, Popconfirm, message } from 'antd';
import { CaretDownOutlined, PlusOutlined } from '@ant-design/icons';
import UserTableContainer from './components/UserTableContainer';
import style from '@/pages/IndexPage.css';

let timer = null;
function UserManager({ dispatch, user, permission  }){
    const { authorized, theme }= user;
    const { depList, currentDep, expandedKeys, roleList, userList, currentPage, total } = permission;
    const [info, setInfo] = useState({});
    const [value, setValue] = useState('');
    const inputRef = useRef();
    useEffect(()=>{
        // 节点切换为区域树下的根节点
        if ( authorized ) {
            dispatch({ type:'permission/fetchDepList'});
            dispatch({ type:'permission/fetchRoleList'});
            dispatch({ type:'permission/fetchUserList'});
        } 
    },[authorized])
    useEffect(()=>{
        if ( info.visible ) {
            if ( info.forEdit ) {
                setValue(currentDep.deptName);
            }
            timer = setTimeout(()=>{
                if ( inputRef.current ) {
                    inputRef.current.focus();         
                }
            },500)     
        }
    },[info])
    useEffect(()=>{
        return ()=>{
            clearTimeout(timer);
            timer = null;
        }
    },[])
    return (
        <div style={{ display:'flex', height:'100%' }}>
            <div style={{ width:'20%', marginRight:'1rem', backgroundColor:'#fff' }}>
                
                <div style={{ display:'flex', flexWrap:'wrap', padding:'1rem' }}>
                    <Button type='primary' ghost style={{ width:'calc( (100% - 1rem)/2 )', margin:'0 1rem 1rem 0'}} onClick={()=>setInfo({ visible:true, isSub:true })}>添加下级</Button>
                    <Button type='primary' ghost style={{ width:'calc( (100% - 1rem)/2 )', margin:'0 0 1rem 0'}} onClick={()=>setInfo({ visible:true })}>添加同级</Button>
                    <Button type='primary' ghost style={{ width:'calc( (100% - 1rem)/2 )', margin:'0 1rem 1rem 0'}} onClick={()=>setInfo({ visible:true, forEdit:true })}>修改</Button>
                    <Popconfirm
                        title={`确认删除${currentDep.deptName}吗?`}
                        okText='确定'
                        cancelText='取消'
                        onConfirm={()=>{
                            // 始终有一个根节点
                            if ( depList.length >1 || currentDep.parentId  ) {
                                new Promise((resolve, reject)=>{
                                    dispatch({ type:'permission/delDepAsync', payload:{ resolve, reject }})
                                }) 
                                .then(()=>{
                                    message.success(`删除${currentDep.deptName}成功`);
                                })
                                .catch(msg=>message.error(msg));
                            } else {
                                message.info('请保持至少有一个根节点');
                            }
                        }}
                    >
                        <Button type='primary' ghost style={{ width:'calc( (100% - 1rem)/2 )', margin:'0 0 1rem 0'}} >删除</Button>
                    </Popconfirm>
                </div>
                
                <div className={style['card-container']} style={{ paddingLeft:'1rem', boxShadow:'none' }}>
                    <Tree 
                        expandedKeys={expandedKeys}
                        onExpand={arr=>{
                            dispatch({ type:'permission/setExpandedKeys', payload:arr });
                        }}
                        showLine={true}
                        switcherIcon={<CaretDownOutlined />}
                        selectedKeys={[currentDep.key]}
                        onSelect={(selectedKeys, { node })=>{
                            dispatch({ type:'permission/setCurrentDep', payload:node });
                        }}
                        treeData={depList}                   
                    />
                </div>
                         
            </div>
            <UserTableContainer 
                userList={userList}
                currentPage={currentPage}
                total={total}
                currentDep={currentDep}
                roleList={roleList}
                depList={depList}
                onDispatch={action=>dispatch(action)}
            />
            {/* 添加部门 */}
            <Modal
                open={Object.keys(info).length ? true : false }
                onCancel={()=>setInfo({})}
                title={ (info.isSub ? '添加下级' : info.forEdit ? '修改' : '添加同级') + '部门' }
                okText='确定'
                cancelText='取消'
                onOk={()=>{
                    if ( value ) {
                        new Promise((resolve, reject)=>{
                            dispatch({ type:'permission/addDepAsync', payload:{ resolve, reject, deptName:value, deptId:info.forEdit ? currentDep.deptId : null, parentDeptId:info.isSub ? currentDep.deptId : null, forEdit:info.forEdit }})
                        })
                        .then(()=>{
                            setInfo({});
                            message.success((info.forEdit ? '修改' : '添加') + '部门成功');
                        })
                        .catch(msg=>message.error(msg))
                    } else {
                        message.info('部门名称不能为空')
                    }
                }}
            >
                <div style={{ padding:'1rem' }}>
                    
                    <Input
                        ref={inputRef}
                        value={value} 
                        onChange={e=>setValue(e.target.value)} 
                    />
                </div>
                
            </Modal>
        </div>
    )
}

export default connect(({ user, permission })=>({ user, permission }))(UserManager);